package club.smartdot.da.config.druid;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

@Configuration
public class DruidConfig {

	@Bean
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource druid() {
		DruidDataSource ds = new DruidDataSource();
		return ds;
	}

	/**
	 * 配置监控服务器
	 *
	 * @return 返回监控注册的servlet对象
	 */
	@Bean
	public ServletRegistrationBean<StatViewServlet> statViewServlet() {
		ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<StatViewServlet>(new StatViewServlet(), new String[] { "/druid/*" });
		Map<String, String> param = new HashMap<>();
		// 添加控制台管理用户
		param.put("loginUsername", "admin");
		param.put("loginPassword", "admin");
		// 添加IP白名单
		param.put("allow", "127.0.0.1");
		// 添加IP黑名单，当白名单和黑名单重复时，黑名单优先级更高
		param.put("deny", "");
		// 是否能够重置数据
		param.put("resetEnable", "false");
		bean.setInitParameters(param);
		return bean;
	}

	@Bean
	public FilterRegistrationBean<WebStatFilter> webStatFilter() {
		FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<WebStatFilter>();
		filterRegistrationBean.setFilter(new WebStatFilter());
		// 添加过滤规则
		filterRegistrationBean.addUrlPatterns(new String[] { "/*" });
		Map<String, String> param = new HashMap<>();
		param.put("exclusions", "*.png,*.woff,*.js,*.css,*.ico,/druid/*");
		// 忽略过滤格式
		filterRegistrationBean.setInitParameters(param);
		return filterRegistrationBean;
	}
}
